<template>
    <div id="app">
        <!-- 顶部标签 -->
        <van-sticky :offset-top="0">        
            <!-- 返回按钮 -->
            <van-nav-bar 
                :title="title" 
                :left-text="navBarLeftText" 
                :left-arrow="showNavBarLeftArrow" 
                @click-left="$router.go(-1)" 
                v-if="vanNavBarShow"
            >
                <template #right>
                    <!-- 右边的加号 --> 
                    <NavPopover :showElement="$route.path == '/message' ? true : false"/>   
                </template>
            </van-nav-bar>
        </van-sticky>

        <!-- 视图 -->
        <Keep-alive :include="includeComponents">
            <router-view />
        </Keep-alive>

        <!-- 底部导航 -->
        <van-tabbar v-if="!hideTabbar" v-model="tabbarActive" active-color="#07c160" @change="changeRoute">
            <van-tabbar-item icon="comment" :badge="unReadMsgSum">信息</van-tabbar-item>
            <van-tabbar-item icon="friends">我的好友</van-tabbar-item>
            <van-tabbar-item>
                我的圈子
                <template #icon>
                    <svg class="icon" aria-hidden="true">
                        <use xlink:href="#icon-pengyouquan"></use>
                    </svg>
                </template>
            </van-tabbar-item>
            <van-tabbar-item>
                我的资料
                <template #icon>
                    <svg class="icon" aria-hidden="true">
                        <use xlink:href="#icon-wodeziliao"></use>
                    </svg>
                </template>
            </van-tabbar-item>
        </van-tabbar>
    </div>
</template>

<script>
    import { mapGetters, mapMutations, mapActions, mapState } from "vuex";
    import NavPopover from "@/components/App/navPopover.vue";
    import { eventBus, eventTypes } from "./utils/event-bus";
    import { setCookie } from '@/utils/token';
    import { Notify, Toast } from "vant";
    import initListeners from "./socket/listeners";

    export default {
        name: "App",
        data() {
            return {
                tabbarActive: 0,
                title: "",
                hideTabbar: false,
            };
        },
        components: {
            NavPopover,
        },
        watch: {
            $route(to, from) {      // 监听路由变化,根据当前路由决定是否显示主页下面选项菜单
                let flag = ["message", "friend", "data", "circle"].includes(to.name);            
                if (!flag) {
                    eventBus.emit(eventTypes.HIDE_TABBAR);
                } else {
                    eventBus.emit(eventTypes.SHOW_TABBAR);
                }

                switch (to.name) {  // 根据路由来显示顶部标题和主页下面选项菜单的选中状态
                    case "message":
                        this.tabbarActive = 0;
                        this.title = "我的信息";
                        break;
                    case "friend":
                        this.tabbarActive = 1;
                        this.title = "通讯录";
                        break;
                    case "friend":
                        this.tabbarActive = 2;
                        this.title = "";
                        break;
                    case "data":
                        this.tabbarActive = 3;
                        this.title = "我的资料";
                        break;
                    case "groupChat":
                        this.title = "发起群聊";
                        break;
                }
            },
        },
        computed: {
            ...mapState(['friendList', 'groupChatList', 'appBottomMenuTagShow']),
            ...mapGetters(["friend_list", "unReadMsgSum"]),
            includeComponents() {   // 根据路由的 meta.keepAlive 属性来动态设置需要缓存的组件，这里是返回一个数组，缓存组件必须有自己的名字，且在路由表中有定义 keepAlive: true
                return this.$router
                    .options.routes
                    .filter(arg => arg.meta.keepAlive)
                    .map(arg => arg.component.name);
            },
            navBarLeftText() {      // 是否显示返回按钮以及按钮旁边显示的文字
                if (["chat", "groupChat", "editDynamics"].includes(this.$route.name)) {
                    return "返回";
                }
                return "";
            },
            showNavBarLeftArrow() { // 是否显示左边箭头
                return ["chat", "groupChat"].includes(this.$route.name);
            },
            vanNavBarShow() {       // 控制顶部的标签栏显示
                return ["message", "friend", "data",  "groupChat"].includes(this.$route.name);
            },
        },
        methods: {  
            ...mapMutations(["upAppBottomMenuTagShow"]),
            ...mapMutations(["upUser", "upGroupChats", 'upFriend']),
            ...mapMutations('newFriend', ['upApplicationStatus', 'pushApplications']),
            ...mapActions('login', ['getFriends', 'getApplications', 'getGroupChats']),
            ...mapActions('newFriend', ['getApplications']),
            changeRoute(index) {       // 点击底部导航切换路由
                switch (index) {
                    case 0:
                        this.$router.push("/message");
                        break;
                    case 1:
                        this.$router.push("/friend");
                        break;
                    case 2:
                        this.$router.push("/circle");
                        break;
                    case 3:
                        this.$router.push("/data");
                        break;
                }
            },
            async initApp(value) {    // 初始化 app
                if (value?.token != undefined) {
                    setCookie(value.token);
                }
                
                if (value.status_code != 200) {
                    Toast.clear();
                    Toast({ icon: "fail", message: value.info });
                    this.tel = "";
                    return;
                }
                this.upUser(value.data);
                Toast.clear();

                let res_friends = await this.getFriends(value.data.phone);  // 获取好友
                if (res_friends.status_code != 200) {
                    Toast.fail(`好友获取失败: ${res_friends.error}`);  
                    return
                }   
                let arr = [];
                res_friends.friends.forEach(item => arr.push(item))
                this.upFriend(arr); // 更新好友列表

                let res_applications =  await this.getApplications(value.data.phone);   // 获取好友申请
                this.pushApplications(res_applications.data);

                let res_groupChats = await this.getGroupChats(value.data.phone);    // 获取群聊
                if (res_groupChats.status_code != 200)
                {
                    this.$toast(`status: ${ res_groupChats.status_code }, err: ${ res_groupChats.data }`);
                    return;
                }
                this.upGroupChats(res_groupChats.data); // 更新群聊列表

                initListeners();    // 初始化监听器

                this.$router.push("/message");
                Notify({ type: "success", duration: 700, message: "登录成功" });
            },
        },
        mounted() {
            eventBus.on(eventTypes.INITAPP, value => this.initApp(value));          // 初始化 app
            eventBus.on(eventTypes.HIDE_TABBAR, () => this.hideTabbar = true);      // 隐藏底部导航
            eventBus.on(eventTypes.SHOW_TABBAR, () => this.hideTabbar = false);     // 显示底部导航
        },
    };
</script>

<style lang="less">
    * {
        margin: 0;
        padding: 0;
        list-style: none;
        text-decoration: none;
        font-family: "微软雅黑";
    }

    #app {
        height: 100vh;
    }
</style>
